package com.sukaiyi.leetcode._125valid_palindrome;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import java.util.HashMap;
import java.util.Map;

/**
 * @author sukaiyi
 * @date 2020/06/19
 * @see <a href="https://leetcode-cn.com/problems/valid-palindrome/>题目地址</a>
 */
public class Solution {

    @Test
    public void test() {
        Assertions.assertTrue(isPalindrome(".,"));
        Assertions.assertTrue(isPalindrome("A man, a plan, a canal: Panama"));
        Assertions.assertFalse(isPalindrome("race a car"));
    }

    public boolean isPalindrome(String s) {
        char[] chars = s.toCharArray();
        if (chars.length <= 1) {
            return true;
        }
        int i = 0;
        int j = chars.length - 1;
        for (; i <= j && !is(chars[i]); i++) ;
        for (; i <= j && !is(chars[j]); j--) ;
        while (i < j) {
            for (; !is(chars[i]); i++) ;
            for (; !is(chars[j]); j--) ;
            if (upper(chars[i]) != upper(chars[j])) {
                return false;
            }
            i++;
            j--;
        }
        return true;
    }

    private boolean is(char c) {
        return c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c >= 'A' && c <= 'Z';
    }

    private char upper(char c) {
        if (c >= 'a' && c <= 'z') {
            return (char) (c - 'a' + 'A');
        }
        return c;
    }
}
